package org.cqut.framework.utils;

import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.Random;

/**
 * @author Mr.X
 */
public class EncryptionUtils {
    /**
     * 随机私有盐值长度
     */
    private static final int SALT_LENGTH = 6;
    /**
     * 公有盐值
     */
    private static final String PUBLIC_SALT = "Course-Website";

    /**
     * 加密用户登陆密码
     * @param password 用户输入密码
     * @param privateSalt 私有盐值（用户注册时间）
     * @return 加密后密码(数据库密码)
     */
    public static String encryptPassword(String password, Date privateSalt){
        String pwd = PUBLIC_SALT + password + privateSalt.toString();
        return DigestUtils.md5DigestAsHex(pwd.getBytes());
    }

    /**
     * 随机私有盐值生成
     * @return 随机盐字符串
     */
    public static String getCharAndNumbers() {
        StringBuilder val = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < SALT_LENGTH; i++) {
            String charOrNumber = (random.nextInt(2) % 2 == 0) ? "char" : "num";
            if ("char".equalsIgnoreCase(charOrNumber)) {
                int choice = (random.nextInt(2) % 2 == 0) ? 65 : 97;
                val.append((char) (choice + random.nextInt(26)));
            } else {
                val.append(String.valueOf(random.nextInt(10)));
            }
        }
        return val.toString();
    }
}
